<?php

namespace app\admin\controller\systemConfig;

use app\admin\model\Config as ConfigModel;
use app\common\controller\Backend;
use app\common\library\Email;
use Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

class Config extends Backend
{
    protected $model = null;

    protected $noNeedLogin = ['index', 'getInitData'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new ConfigModel();
    }

    public function index()
    {
        try {
            // 剥去字符串中的HTML标签以及左右两边的空格
            $this->request->filter(['strip_tags', 'trim']);
            if (stringToBoolean($this->request->param('select'))) {
                // 下拉框数据接口
                $this->select();
            }
            // 生成搜索条件、排序等
            list($where, $alias, $limit, $order) = $this->queryBuilder();
            $res = $this->model
                ->field($this->indexField)
                ->withJoin($this->withJoinTable, $this->withJoinType)
                ->alias($alias)
                ->where($where)
                ->order($order)
                ->paginate($limit);

            $this->success('', [
                'list'   => $res->items(),
                'total'  => $res->total(),
                'remark' => get_route_remark(),
            ]);
        } catch (DbException $ex) {
            $this->success('', [
                'list'   => [],
                'total'  => 0,
                'remark' => get_route_remark(),
            ]);
        }
    }

    /**
     * 编辑
     * @param null $id
     */
    public function edit($id = null)
    {
        if (empty($id)) {
            $this->error(__('Record not found'));
        }
        $row = $this->model->find($id);
        if(!$row){
            $this->error('未找到记录');
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if($this->request->isPost()){
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) {
                            // 启用模型场景验证
                            $validate->scene('edit');
                        }
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $contentStr = '';
        if(!empty($row['content'])){
            $content = $row['content'];
            foreach ($content as $key=>$val){
                if(in_array($row['type'], $this->model->objectArray)){
                    if(empty($contentStr)){
                        $contentStr = $val['key'] . '=' . $val['name'];
                    }else{
                        $contentStr .= "\n" . $val['key'] . '=' . $val['name'];
                    }
                }else{
                    if(empty($contentStr)){
                        $contentStr = $key . '=' . $val;
                    }else{
                        $contentStr .= "\n" . $key . '=' . $val;
                    }
                }

            }
        }
        $extendStr = '';
        if(!empty($row['extend'])){
            $extend = $row['extend'];
            foreach ($extend as $key=>$val){
                if(empty($extendStr)){
                    $extendStr = $key . '=' . $val;
                }else{
                    $extendStr .= "\n" . $key . '=' . $val;
                }
            }
        }
        $row['contentStr'] = $contentStr;
        $row['extendStr'] = $extendStr;
        $this->success('', [
            'row' => $row
        ]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Cache::tag(ConfigModel::$cacheTag)->clear();
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function sendTestMail()
    {
        $data = $this->request->post();
        $mail = new Email();
        try {
            $mail->Host       = $data['smtp_server'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $data['smtp_user'];
            $mail->Password   = $data['smtp_pass'];
            $mail->SMTPSecure = $data['smtp_verification'] == 'SSL' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = $data['smtp_port'];

            $mail->setFrom($data['smtp_sender_mail'], $data['smtp_user']);

            $mail->isSMTP();
            $mail->addAddress($data['testMail']);
            $mail->isHTML();
            $mail->setSubject(__('This is a test email') . '-' . get_sys_config('site_name'));
            $mail->Body = __('Congratulations, receiving this email means that your email service has been configured correctly');
            $mail->send();
        } catch (PHPMailerException $e) {
            $this->error($mail->ErrorInfo);
        }
        $this->success(__('Test mail sent successfully~'));
    }

    /**
     * 获取初始化数据
     * @return void
     */
    public function getInitData(): void
    {
        $ruleList = verifyMode();
        $typeList = variableTypeSelect();

        $this->success('', [
            'rule_list' => $ruleList,
            'type_list' => $typeList,
        ]);
    }

}
